// pnpm install -D @types/element-resize-detector && pnpm install element-resize-detector
import elementResizeDetectorMaker from "element-resize-detector";
import {Directive, VNode} from "@vue/runtime-core";
// 创建实例 使用超快的基于滚动的方法
const elListen: elementResizeDetectorMaker.Erd = elementResizeDetectorMaker({
  strategy: "scroll",
  callOnAdd: true
})

export interface BindFuncParams {
  el: HTMLElement;

  [key: string]: any;
}

export interface BindValue {
  func: (funcParams: BindFuncParams) => void;
  funcParams: BindFuncParams;
  /**
   * 是否立即执行一次
   */
  immediate: boolean;
}

export const ElementResize: Directive<HTMLElement, BindValue> = {
  mounted(el, binding, vnode: VNode, prevVNode) {
    let bindValue: BindValue = binding.value
    if (bindValue.immediate) {
      bindValue.func({
        el,
        ...bindValue.funcParams
      })
    }
    elListen.listenTo(el, () => {
      bindValue.func({
        el,
        ...bindValue.funcParams
      })
    })
  },
  beforeUnmount(el, binding, vnode: VNode, prevVNode) {
    elListen.uninstall(el)
  }
}
